package cmd

import (
	"bytes"
	"fmt"
	"strconv"
	"time"

	"github.com/pingcap/tidb/config"
	"github.com/pingcap/tidb/store/tikv"
	"github.com/spf13/cobra"
)

var archive3Cmd = &cobra.Command{
	Use:   "scan",
	Short: "Archive He3DB Xlog KV",
	Long:  "Welcome to use hbr for He3DB xlog archive",
	Run:   runArchive3,
}

func init() {
	rootCmd.AddCommand(archive3Cmd)
}

func runArchive3(cmd *cobra.Command, args []string) {
	archiveStart := time.Now()
	access_key, _ := cmd.Flags().GetString("access_key")
	secret_key, _ := cmd.Flags().GetString("secret_key")
	endpoint, _ := cmd.Flags().GetString("endpoint")
	region, _ := cmd.Flags().GetString("region")
	bucket, _ := cmd.Flags().GetString("bucket")
	pd, _ := cmd.Flags().GetString("pd")
	backup_name, _ := cmd.Flags().GetString("name")
	archive_start_time_line, _ := cmd.Flags().GetString("archive_start_time_line")
	archive_start_lsn, _ := cmd.Flags().GetString("archive_start_lsn")

	if access_key == "" || secret_key == "" || endpoint == "" || region == "" || bucket == "" || pd == "" || backup_name == "" || archive_start_time_line == "" || archive_start_lsn == "" {
		fmt.Printf("PARAMETER ERROR!\n")
		return
	}

	client, err := tikv.NewRawKVClient([]string{pd}, config.Security{})
	if err != nil {
		fmt.Printf("Connect Tikv Error!\n%v\n", err)
		return
	}

	wlCount := 0

	// archive wal kv
	fmt.Printf("archive wal kv!\n")
	//0600000000000000010000000000000000
	retStartString := fmt.Sprintf("06%s%s", archive_start_time_line, archive_start_lsn)
	retEndString := "06ffffffffffffffffffffffffffffffff"

	retStart := make([]byte, 17)
	retEnd := make([]byte, 17)
	index := 0
	for i := 0; i < len(retStartString); i += 2 {
		value, _ := strconv.ParseUint(retStartString[i:i+2], 16, 8)
		retStart[index] = byte(0xff & value)
		value, _ = strconv.ParseUint(retEndString[i:i+2], 16, 8)
		retEnd[index] = byte(0xff & value)
		index++
	}
	fmt.Printf("%x\n", retStart)
	fmt.Printf("%x\n", retEnd)

	limit := 10240

	for {
		keys, _, _ := client.Scan(retStart, retEnd, limit)
		for k, _ := range keys {
			fmt.Printf("%x\n", keys[k])

			if bytes.Compare(retStart, keys[k]) < 0 {
				retStart = keys[k]
			}
			wlCount++
		}
		if len(keys) < limit {
			break
		}
		wlCount--
	}

	//wg.Wait()
	client.Close()

	fmt.Printf("wal kv count:%v\n", wlCount)
	fmt.Println("backup time:", time.Since(archiveStart))
}
